package net.sunzc.takephoto;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.ImageView;
import com.hanvon.faceRec.FaceCoreHelper;
import com.hanvon.faceRec.OUserInfo;
import net.sunzc.hwfacetest.utils.FileUtils;
import net.sunzc.takephoto.utils.MyLog;
import net.sunzc.takephoto.utils.ProgressAsyncTask;
import net.sunzc.takephoto.utils.ViewUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 启动的时候重建featureFile
 * 重新注册faceEngine
 * 退出后不清除
 * Created by Administrator on 2017/1/16.
 */
public class FaceCollector extends HWFace {
    private static final String TAG = "FaceCollector";
    private static final String DIALOG_TITLE = "人脸采集";
    private List<byte[]> mFeatureDatas = new ArrayList<>();
    private OUserInfo mUserInfo;

    public FaceCollector(Context context, ICamera camera, String userName) {
        super(context, camera);
        MyLog.i(TAG, "featureFile是否存在:" + getFeatureFile().exists());
        byte[] mFeatureFileBytes = initFeatureFile();
        FaceCoreHelper.InitFaceEngine(mFeatureFileBytes, mFeatureFileBytes.length, FaceCoreHelper.SERIAL_NUMBER);
        mUserInfo = createUserInfo(userName, camera.getPictureSize());
    }

    public static byte[] getLocalPicFeature(byte[] imageGrayData, int width, int height, int[] facePos) {
        int[] size = new int[1];
        FaceCoreHelper.GetFeatureSize(size);
        byte[] feature = new byte[size[0]];
        int[] eyePos = new int[6];
        System.arraycopy(facePos, 5, eyePos, 0, 4);
        FaceCoreHelper.GetFaceFeatureEx(imageGrayData, width, height, eyePos, feature);
        return feature;
    }

    private OUserInfo createUserInfo(String userName, ICamera.Size size) {
        OUserInfo info = new OUserInfo();
        info.strName = userName;
        info.nImgNum = TEMPLATE_SIZE;
        info.pbImageArray = new byte[size.width * size.height * 2 * TEMPLATE_SIZE];
        info.pFacePos = new int[12 * 16];
        info.nWidth = size.width;
        info.nHeight = size.height;
        return info;
    }

    public void setCollectListener(CollectionListener listener) {
        setFaceListener(listener);
    }

    private void nextCollect(final byte[] feature) {
        new ProgressAsyncTask<byte[], String>(mContext) {
            @Override
            protected void onPreExecute() {
                getProgressBar().setProgressStyle(ProgressDialog.STYLE_SPINNER);
                getProgressBar().setTitle("正在处理……");
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(byte[]... params) {
                mFeatureDatas.add(params[0]);
                if (mFeatureDatas.size() == TEMPLATE_SIZE && mFaceListener != null) {
                    byte[] features = FileUtils.list2Array(mFeatureDatas);
                    int[] id = new int[1];
                    int[] dataSize = new int[1];
                    byte[] featureMem = new byte[15000];
                    FaceCoreHelper.AddUserWithFeatures(features, mUserInfo.strName, TEMPLATE_SIZE, id, featureMem, dataSize);
                    FileUtils.writeFile(getFeatureFile(), featureMem, dataSize[0]);
                    MyLog.i(TAG, "添加用户-->" + id[0] + "数据长度:" + dataSize[0]);
                    return FileUtils.readOriginal2Hex(getFeatureFile());
                }
                return null;
            }

            @Override
            protected void onPostExecute(String face) {
                super.onPostExecute(face);
                if (!TextUtils.isEmpty(face)) {
                    ((CollectionListener) mFaceListener).onFinish(face);
                } else {
                    collectFace();
                }
            }
        }.execute(feature);
    }

    public void collectFace() {
        checkFace(new FaceCheckListener() {
            @Override
            public void onCheckSuccess(Bitmap bitmap, byte[] featureFromImage, int[] facePos) {
                byte[] featureData = getLocalPicFeature(featureFromImage, bitmap.getWidth(), bitmap.getHeight(), facePos);
                MyLog.i(TAG, "采集成功第" + mFeatureDatas.size() + "次,共需采集" + TEMPLATE_SIZE + "次" + "内容:" + Arrays.toString(featureData));
                ViewUtils.showToast(mContext, "采集成功第" + mFeatureDatas.size() + "次,共需采集" + TEMPLATE_SIZE + "次");
                if (mFaceListener != null) {
                    ((CollectionListener) mFaceListener).onCollect(mFeatureDatas.size(), bitmap);
                }
                nextCollect(featureData);
            }

            @Override
            public void onCheckFailure(Bitmap bitmap) {
                ImageView view = ViewUtils.getImageView(mContext, bitmap);
                MyLog.e(TAG, "人脸采集错误，请重新采集");
                ViewUtils.showDialog(mContext, DIALOG_TITLE, "人脸采集错误，请重新采集", true, view, "重新采集", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        collectFace();
                    }
                });
            }
        });
    }

    public interface CollectionListener extends IFace {
        void onCollect(int count, Bitmap bitmap);

        void onFinish(String faceFeature);
    }
}
